package com.youlin.config;

import com.google.common.collect.Maps;
import org.redisson.Redisson;
import org.redisson.RedissonNode;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.RedissonNodeConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//@Configuration
public class RedissonAutoConfiguration {

    /**
     * 单机模式自动装配
     * @return
     */
//    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer()
                // use "rediss://" for SSL connection
//                .setAddress("redis://192.168.182.123:6379")
                .setAddress("redis://192.168.1.123:6379")
                .setPassword("YlRedis@2018")
                .setDatabase(8)
                .setTimeout(30000);
        return Redisson.create(config);
    }

    /**
     * 集群模式自动装配
     * @return
     */
//    @Bean
//    @DependsOn("lettuceConnectionFactory")
    public RedissonClient redissonClient(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisClusterConfiguration clusterConfiguration = lettuceConnectionFactory.getClusterConfiguration();
        List<String> clusterNodes = clusterConfiguration.getClusterNodes().parallelStream().map(redisNode ->
                        "redis://" + redisNode.getHost() + ":" + redisNode.getPort()).collect(Collectors.toList());
        String[] clusterNodesArr = clusterNodes.toArray(new String[clusterNodes.size()]);
        Config config = new Config();
        config.useClusterServers().addNodeAddress(clusterNodesArr);
        return Redisson.create(config);
    }

//    @Bean
//    @DependsOn("redissonClient")
    public RedissonNode redissonNode (RedissonClient redissonClient) {
        Config config = redissonClient.getConfig();
        RedissonNodeConfig nodeConfig = new RedissonNodeConfig(config);
        Map<String, Integer> workers = Maps.newHashMap();
        workers.put("myExecutor-1", 1);
        workers.put("myExecutor-2", 2);
        workers.put("myExecutor-3", 3);
        nodeConfig.setExecutorServiceWorkers(workers);
        return RedissonNode.create(nodeConfig, redissonClient);
    }

}